#include <iostream>
#include "../include/server.hpp"

Muduo::EventLoop baseLoop;
uint64_t connId = 0;
Muduo::LoopThreadPool* loopPool;

std::unordered_map<uint64_t, Muduo::PtrConnection> _conns;//用来管理所有的连接
void ConnectionDestroy(const Muduo::PtrConnection& conn)
{
    _conns.erase(conn->Id());
}
void OnConnected(const Muduo::PtrConnection& conn)
{
    LOGDEBUG("new connection: %p", conn.get());
}
void OnMessage(const Muduo::PtrConnection& conn, Muduo::Buffer* buf)
{
    buf->MoveReadOffest(buf->ReadAbleSize());
    std::string str = "hello client!";
    conn->Send(str.c_str(), str.size());
}

void NewConnection(int fd)
{
    connId++;
    Muduo::PtrConnection conn(new Muduo::Connection(loopPool->NextLoop(), connId, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));
    conn->SetCloseCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->EnableInactiveRelease(10);
    conn->Established();//就绪初始化
    _conns.insert(std::make_pair(connId, conn));
    LOGDEBUG("set a new connection---------");
}

int main()
{
    loopPool = new Muduo::LoopThreadPool(&baseLoop);
    loopPool->SetThreadCount(2);
    loopPool->Create();
    Muduo::Acceptor acceptor(&baseLoop, 8888);
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));
    acceptor.Listen();
    baseLoop.Start();
    return 0;
}